package com.smf.lsc.global.id;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;

/***
 * 全局ID-基于redis-incr，增加锁控制
 * @author ln 2021-11-30
 *
 */
public class RedisGlobalIdImpl implements GlobalId{
	private static Map<String, List<Long>> map = null;
	private final String GLOBALID_KEY="globalId";
	static {
		map = new HashMap<String, List<Long>>();
	}
	
	/**
	 * key超时时间
	 */
	private final long LIVE_TIME=-1;
	
	/**
	 * redis步长
	 */
	@Value("${global.id.step:10}")
	private int step;
	
	@Autowired
    RedisTemplate redisTemplate;
	
    private Long doWorkId(String key,int length) {
    	synchronized(this)
    	{
	    	Long increment;
	    	if(map.get(key)==null ||  map.get(key).size()==0)
	    	{
	    		List<Long> listId=new ArrayList<Long>();
		        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
		        long ss=entityIdCounter.addAndGet(length);
		        //初始设置过期时间
		        if (ss == 0) {
		            entityIdCounter.expire(LIVE_TIME, TimeUnit.SECONDS);
		        }
		        for(int i=length;i>0;i--)
		        {
		        	listId.add(ss-i);
		        }
		        map.put(key, listId);
	    	}
	    	increment=getNum(key);
	        return increment;
    	}
    }
    
    private long getNum(String key) {
		long count=0;
		if(map.get(key)!=null)
		{
			count = map.get(key).get(0);
			map.get(key).remove(0);
		}
		return count;
	}

    public Long getId(String key) {
		// TODO Auto-generated method stub
		return doWorkId(key,step);
	}
    
	public Long getId() {
		// TODO Auto-generated method stub
		return doWorkId(GLOBALID_KEY,step);
	}
	
}
